/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.studentevaluate.web;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolationException;

import cn.hutool.core.util.ObjectUtil;
import com.jeeplus.config.shiro.redis.RedisCache;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.StudentMoreduMain;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.mapper.UserMapper;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.studentevaluate.entity.StudentEvaluate;
import com.jeeplus.modules.studentevaluate.service.StudentEvaluateService;

/**
 * 学生评价Controller
 * @author 秦子洋
 * @version 2022-03-02
 */
@RestController
@RequestMapping(value = "/studentevaluate/studentEvaluate")
public class StudentEvaluateController extends BaseController {

	@Autowired
	private StudentEvaluateService studentEvaluateService;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	@Qualifier("longRedisTemplate")
	private RedisTemplate<String,Object> redisTemplate;


	@ModelAttribute
	public StudentEvaluate get(@RequestParam(required=false) String id) {
		StudentEvaluate entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = studentEvaluateService.get(id);
		}
		if (entity == null){
			entity = new StudentEvaluate();
		}
		return entity;
	}

	/**
	 * 学生评价列表数据
	 */
	@RequiresPermissions("studentevaluate:studentEvaluate:list")
	@GetMapping("list")
	public AjaxJson list(StudentEvaluate studentEvaluate, HttpServletRequest request, HttpServletResponse response) {
		Page<StudentEvaluate> page = studentEvaluateService.findPage(new Page<StudentEvaluate>(request, response), studentEvaluate);
		return AjaxJson.success().put("page",page);
	}
	@RequiresPermissions("studentevaluate:studentEvaluate:list")
	@GetMapping("queryPinyin")
	public AjaxJson queryPinyin() {
		List nameList = studentEvaluateService.queryName();
		List instituteList = studentEvaluateService.queryInstitute();
		List teacherList = studentEvaluateService.queryTeacher();
		return AjaxJson.success().put("nameList",nameList).put("instituteList",instituteList).put("teacherList",teacherList);
	}
	/**
	 * 根据Id获取学生评价数据
	 */
	@RequiresPermissions(value={"studentevaluate:studentEvaluate:view","studentevaluate:studentEvaluate:add","studentevaluate:studentEvaluate:edit"},logical=Logical.OR)
	@GetMapping("queryById")
	public AjaxJson queryById(StudentEvaluate studentEvaluate) {
		return AjaxJson.success().put("studentEvaluate", studentEvaluate);
	}

	/**
	 * 一键导入所有用户接口
	 */
	@RequiresPermissions(value={"studentevaluate:studentEvaluate:imp"})
	@GetMapping("allin")
	public AjaxJson allin () {
		User user = new User();
		Role role = new Role();
		role.setId("b930ac75924c47f99ac92c6fc8c3accb"); //一般账号id
		user.setRole(role);
		List<User> list = userMapper.findList(user);
		for (User a: list) {
			StudentEvaluate studentEvaluate = new StudentEvaluate();
			studentEvaluate.setName(a.getName());  //姓名
			studentEvaluate.setInstitute(a.getOffice().getName()); //学院
			studentEvaluate.setGrade(a.getGrade()); //年级
			studentEvaluate.setClasse(a.getClassn()); //班级
			studentEvaluate.setTeacher(a.getTeacher()); // 辅导员老师
			studentEvaluate.setStudentId(a.getNo()); //学号
			studentEvaluate.setEvaluate("未评价"); //是否评价
			studentEvaluate.setState(a.getState()); // 学籍状态

			studentEvaluateService.save(studentEvaluate); //保存
		}
		deleteCache();
		return AjaxJson.success("导入成功");
	}
	/**
	 *
	 * 保存学生评价
	 */
	@RequiresPermissions(value={"studentevaluate:studentEvaluate:add","studentevaluate:studentEvaluate:edit"},logical=Logical.OR)
	@PostMapping("save")
	public AjaxJson save(StudentEvaluate studentEvaluate, Model model) throws Exception{
		deleteCache();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(studentEvaluate);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		if (studentEvaluate.getSignature() != null) {
			if (studentEvaluate.getSignature().indexOf("/nginx-1.23.2/html") >= 0){
				String[] url =  studentEvaluate.getSignature().split("/nginx-1.23.2/html");
				//新增或编辑表单保存
				studentEvaluate.setSignature(url[1]);
			}
		}
		studentEvaluateService.save(studentEvaluate);//保存
		return AjaxJson.success("保存学生评价成功");
	}

	@PostMapping("createfa")
	public AjaxJson create() throws Exception{
		deleteCache();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String nameList[] = {"张", "沈", "王", "郭", "羊", "孙", "陈", "于", "赵", "清", "空", "换", "细", "狗", "保", "存", "所"};
		String clas[] = {"法学一班","法学二班","法学三班"};
		String teacher = "张大三";
		String no[] = {"1","2","3","4","5","6","7","8","9","0"};
		String state = "在籍";
		String relation = "父子";
		String add[] = {"新疆", "西藏", "云南", "青海", "甘肃", "四川", "重庆", "贵州", "广西", "海南", "澳门", "广东", "香港", "湖南", "湖北", "陕西", "宁夏", "内蒙古", "河北", "北京", "天津", "山东", "河南", "安徽", "江西", "福建", "台湾", "浙江", "上海", "江苏", "辽宁", "吉林", "黑龙江"};
		for (int i = 0; i < 1000; i++){
			StudentEvaluate studentEvaluate = new StudentEvaluate();
			Random rand = new Random();
			studentEvaluate.setName(nameList[rand.nextInt(nameList.length)]+nameList[rand.nextInt(nameList.length)]+nameList[rand.nextInt(nameList.length)]);
			studentEvaluate.setInstitute("法学院");
			studentEvaluate.setClasse(clas[rand.nextInt(clas.length)]);
			studentEvaluate.setTeacher(teacher);
			studentEvaluate.setStudentId(no[rand.nextInt(no.length)]+no[rand.nextInt(no.length)]+no[rand.nextInt(no.length)]+no[rand.nextInt(no.length)]+no[rand.nextInt(no.length)]+no[rand.nextInt(no.length)]+no[rand.nextInt(no.length)]+no[rand.nextInt(no.length)]+no[rand.nextInt(no.length)]+no[rand.nextInt(no.length)]);
			studentEvaluate.setEvaluate("已评价");
			studentEvaluate.setState("在籍");
			studentEvaluate.setRelationship(relation);
			studentEvaluate.setAddress(add[rand.nextInt(add.length)]);
			studentEvaluateService.save(studentEvaluate);//保存
		}
		return AjaxJson.success("保存学生评价成功");
	}


	/**
	 * 批量删除学生评价
	 */
	@RequiresPermissions("studentevaluate:studentEvaluate:del")
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			studentEvaluateService.delete(new StudentEvaluate(id));
		}
		return AjaxJson.success("删除学生评价成功");
	}
	@RequiresPermissions("studentevaluate:studentEvaluate:list")
	@PostMapping("reEvaluate")
	public AjaxJson reEvaluate(String ids) {
		deleteCache();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			studentEvaluateService.reEvaluate(new StudentEvaluate(id));
		}
		return AjaxJson.success("打回学生评价成功");
	}
	/**
	 * 删除所有学生评价
	 */
	@RequiresPermissions("studentevaluate:studentEvaluate:imp")
	@DeleteMapping("delall")
	public AjaxJson delall() {
		studentEvaluateService.delall();
		deleteCache();
		return AjaxJson.success("删除学生评价成功");
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("studentevaluate:studentEvaluate:export")
    @GetMapping("export")
    public AjaxJson exportFile(StudentEvaluate studentEvaluate, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "学生评价"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<StudentEvaluate> page = studentEvaluateService.findPage(new Page<StudentEvaluate>(request, response, -1), studentEvaluate);
    		new ExportExcel("学生评价", StudentEvaluate.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error("导出学生评价记录失败！失败信息："+e.getMessage());
		}
    }
	/**
	 * @Description:导出excel @param @return @throws
	 */
//	@ResponseBody
	@GetMapping("exportnew")
	public void UserExcelDownloads(StudentEvaluate studentEvaluate, HttpServletRequest request, HttpServletResponse response) throws IOException {

		try {
			int a = 0;
			List<StudentEvaluate> temperatureRecordLists = new ArrayList<>();
			HSSFWorkbook workbook = new HSSFWorkbook();
			HSSFSheet sheet = workbook.createSheet();
			// 设置要导出的文件的名字
			String fileName = "测温数据"  + ".xls";

			// 新增数据行，并且设置单元格数据
			int rowNum = 1;
			//这里是你要导出表格第一行的标题，要几个自己加上去
			String[] headers = { "姓名", "学院", "年级", "班级", "辅导员", "学号", "是否评价", "手写签名", "学籍状态",
					"家长电话号码","与学生的关系","家庭住址" };
			System.out.println("newSuccess");
			// headers表示excel表中第一行的表头
			HSSFRow row = sheet.createRow(0);

			// 在excel表中添加表头
			for (int i = 0; i < headers.length; i++) {
				HSSFCell cell = row.createCell(i);
				HSSFRichTextString text = new HSSFRichTextString(headers[i]);
				cell.setCellValue(text);
			}
			// 单独设置列宽，第一个参数代表列id(从0开始),第2个参数代表宽度值
			sheet.setColumnWidth(9, 4300);
			sheet.setColumnWidth(5, 7000);
			sheet.setColumnWidth(4, 4800);
			sheet.setColumnWidth(3, 3000);
			sheet.setColumnWidth(2, 3000);
			sheet.setColumnWidth(8, 5000);
			sheet.setColumnWidth(7, 7000);
			sheet.setColumnWidth(10, 7000);
			sheet.setColumnWidth(11, 7000);
			sheet.setColumnWidth(12, 7000);
			//数据库查询出数据
			temperatureRecordLists = studentEvaluateService.findList(studentEvaluate);


			// 在表中存放查询到的数据放入对应的列
			for (StudentEvaluate temperatureRecord : temperatureRecordLists) {
				HSSFRow row1 = sheet.createRow(rowNum);
				// 设置行高
				row1.setHeight((short) 1500);
				row1.createCell(0).setCellValue(temperatureRecord.getName());
				row1.createCell(1).setCellValue(temperatureRecord.getInstitute());
				row1.createCell(2).setCellValue(temperatureRecord.getGrade());
				row1.createCell(3).setCellValue(temperatureRecord.getClasse());
				row1.createCell(4).setCellValue(temperatureRecord.getTeacher());
				row1.createCell(5).setCellValue(temperatureRecord.getStudentId());
				row1.createCell(6).setCellValue(temperatureRecord.getEvaluate());
//				row1.createCell(7).setCellValue(temperatureRecord.getSignature());
				row1.createCell(8).setCellValue(temperatureRecord.getState());
				row1.createCell(9).setCellValue(temperatureRecord.getTelphone());
				row1.createCell(10).setCellValue(temperatureRecord.getRelationship());
				row1.createCell(11).setCellValue(temperatureRecord.getAddress());




//				if (temperatureRecord.getFloor() == null) {
//					row1.createCell(6).setCellValue("");
//				} else {
//					row1.createCell(6).setCellValue(temperatureRecord.getFloor());
//				}
//				row1.createCell(8).setCellValue(temperatureRecord.getxPoint() + ":" + temperatureRecord.getyPoint()
//						+ ":" + temperatureRecord.getzPoint());

				/* 图片处理，数据库存图片路径，如果导出的时候在服务器没有该图片，
				则导出时候显示的我们自己默认的图片nullPhoto.jpg，
				如果默认图片也不存在，则导出文字。相应逻辑可以自己修改。
				如果不需要导出图片，删掉这部分即可*/
				String PREFIX = "C:\\software\\nginx\\nginx-1.23.2\\html";
//				String PREFIX = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
				File l = new File(fileName);
				String path =PREFIX
						+ temperatureRecord.getSignature();
				String nullpath = PREFIX
						+ "\\userfiles\\myphoto.png";

				File file;
				// 正常情况下path为数据库图片在服务器的路径，一定存在。
				if (path == null || path.length() < 0) {
					file = new File(nullpath);
					if (file.exists()) {
						setPhoto(workbook, sheet, a, file);
					} else {
						row1.createCell(7).setCellValue("暂无图片");
					}

				} else {
					file = new File(path);
					// 二次判断，判断文件是否存在
					if (file.exists()) {
						setPhoto(workbook, sheet, a, file);
					} else {
						file = new File(nullpath);
						if (file.exists()) {
							setPhoto(workbook, sheet, a, file);
						} else {
							row1.createCell(7).setCellValue("暂无图片");
						}

					}
				}
				rowNum++;
				a++;
			}

			// 写入excel文件
			// 设置生成的Excel的文件名，并以中文进行编码
			response.reset();
//			String codedFileName = new String(("德育评价").getBytes("gbk"), "iso-8859-1");
			response.setHeader("Content-Disposition", DateUtils.getDate("yyyyMMddHHmmss") + ".xls");
			// 响应类型,编码
			response.setContentType("application/octet-stream;charset=UTF-8");
			// 形成输出流
			OutputStream osOut = response.getOutputStream();
			// 将指定的字节写入此输出流
			workbook.write(osOut);
			// 刷新此输出流并强制将所有缓冲的输出字节被写出
			osOut.flush();
			// 关闭流
			osOut.close();
			/*
			 * dispose of temporary files backing this workbook on disk 处理在磁盘上备份此工作簿的临时文件
			 * SXSSF分配临时文件，您必须始终清除显式，通过调用dispose方法
			 */

		} catch (Exception e) {
			e.printStackTrace();
			response.sendRedirect("error.action");
		}

	}
	/**
	 * @Title: @Description: excel生成图片工具 @param @return @throws
	 */
	public void setPhoto(HSSFWorkbook workbook, HSSFSheet sheet, int a, File file) {
		HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
		BufferedImage bufferImg = null;
		ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();

		try {
			bufferImg = ImageIO.read(file);
//				bufferImg = ImageIO.read(new File(ClassUtils.getDefaultClassLoader().getResource("static").getPath()
//				+ temperatureRecord.getPhotoUrl()));
			ImageIO.write(bufferImg, "png", byteArrayOut);
			// anchor主要用于设置图片的属性
			HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 7, a + 1, (short) 7, a + 1);
			anchor.setAnchorType(ClientAnchor.AnchorType.byId(3));
			// 插入图片
			patriarch.createPicture(anchor,
					workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
//				System.out.println("----Excle文件已生成------");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}



	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("studentevaluate:studentEvaluate:import")
    @PostMapping("import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		deleteCache();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<StudentEvaluate> list = ei.getDataList(StudentEvaluate.class);
			for (StudentEvaluate studentEvaluate : list){
				try{
					studentEvaluateService.save(studentEvaluate);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条学生评价记录。");
			}
			return AjaxJson.success( "已成功导入 "+successNum+" 条学生评价记录"+failureMsg);
		} catch (Exception e) {
			return AjaxJson.error("导入学生评价失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 下载导入学生评价数据模板
	 */
	@RequiresPermissions("studentevaluate:studentEvaluate:import")
    @GetMapping("import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		try {
            String fileName = "学生评价数据导入模板.xlsx";
    		List<StudentEvaluate> list = Lists.newArrayList();
    		new ExportExcel("学生评价数据", StudentEvaluate.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error( "导入模板下载失败！失败信息："+e.getMessage());
		}
    }

	public void deleteCache () {
		String keyPre = "StudentEvaluate";
		System.out.println("nihao");
		Set<String> keys = redisTemplate.keys("*");
		// 如果存在key，则逐个删除
		if (!keys.isEmpty()) {
			redisTemplate.delete(keys);
		}

//		System.out.println(keys.size());
//		if (ObjectUtil.isNotEmpty(keys)) {
//			System.out.println("wolaile");
//			redisTemplate.delete(keys);
//		}
//		Set keys1 = redisTemplateObject.keys(keyPre + "*");
//		if (ObjectUtil.isNotEmpty(keys1)) {
//			redisTemplateObject.delete(keys1);
//		}


	}


}